package com.rosh.rpc.server.register.zk;

import com.rosh.rpc.core.annotation.RoshRpcService;
import com.rosh.rpc.core.spring.SpringBeanFactory;
import com.rosh.rpc.core.utils.IpUtils;
import com.rosh.rpc.server.config.RpcServerConfiguration;
import com.rosh.rpc.server.register.RpcRegistry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import java.util.Map;

@Configuration
@Slf4j
@DependsOn("springBeanFactory")
public class ZkRegistry implements RpcRegistry {


    @Autowired
    private ZkServerUtils zkServerUtils;

    @Autowired
    private RpcServerConfiguration rpcServerConfiguration;


    @Override
    public void serviceRegistry() {

        //找RoshRpcService注解，像注册中心注册服务
        Map<String, Object> map = SpringBeanFactory.getBeanListByAnnotationClass(RoshRpcService.class);
        //如果map不为空，那么注册
        if (!map.isEmpty()) {
            //获取ip
            String ip = IpUtils.getRealIp();
            //创建根节点
            zkServerUtils.createRootNode();
            //创建服务
            for (Object bean : map.values()) {
                //拿到注解
                RoshRpcService rpcService = bean.getClass().getAnnotation(RoshRpcService.class);
                //拿到接口
                Class<?> interfaceClass = rpcService.interfaceClass();
                //获取接口名称
                String serviceName = interfaceClass.getName();
                //创建接口节点
                zkServerUtils.createPersistentNode(serviceName);
                //接口下面创建提供者信息节点
                String providerNode = serviceName + "/" + ip + ":" + rpcServerConfiguration.getRpcPort();
                zkServerUtils.createNode(providerNode);
                log.info("注册服务信息为: serviceName:{},providerNode:{}", serviceName, providerNode);
            }
        }

    }
}
